package cn.iocoder.yudao.module.product.service.customermessage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.product.controller.app.customermessage.vo.AppCustomerMessagePageReqVO;
import cn.iocoder.yudao.module.product.controller.app.customermessage.vo.AppCustomerMessageReqVO;
import cn.iocoder.yudao.module.product.controller.app.customermessage.vo.AppCustomerMessageRespVO;
import cn.iocoder.yudao.module.promotion.api.article.ArticleApi;
import cn.iocoder.yudao.module.promotion.api.article.dto.ArticleRespDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import cn.iocoder.yudao.module.product.controller.admin.customermessage.vo.*;
import cn.iocoder.yudao.module.product.dal.dataobject.customermessage.CustomerMessageDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.product.dal.mysql.customermessage.CustomerMessageMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.*;

/**
 * 客服消息 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class CustomerMessageServiceImpl implements CustomerMessageService {

    @Resource
    private CustomerMessageMapper customerMessageMapper;
    @Resource
    private ArticleApi articleApi;
    @Value("${customer.message.answer:对话框输入【数字】，选择您要处理的问题类型}")
    private String customerMessageAnswer;

    @Override
    public Long createCustomerMessage(CustomerMessageSaveReqVO createReqVO) {
        // 插入
        CustomerMessageDO customerMessage = BeanUtils.toBean(createReqVO, CustomerMessageDO.class);
        customerMessageMapper.insert(customerMessage);
        // 返回
        return customerMessage.getId();
    }

    @Override
    public AppCustomerMessageRespVO createCustomerMessage(AppCustomerMessageReqVO createReqVO) {
        LoginUser loginUser = Optional.ofNullable(SecurityFrameworkUtils.getLoginUser())
                .orElseThrow(() -> new ValidateException("用户未登录"));
        if (Objects.isNull(createReqVO.getSendTime())) {
            createReqVO.setSendTime(LocalDateTime.now());
        }
        createReqVO.setUserId(loginUser.getId());
        CustomerMessageDO customerMessage = BeanUtils.toBean(createReqVO, CustomerMessageDO.class);
        customerMessageMapper.insert(customerMessage);
        if (!createReqVO.isOnline() && createReqVO.getSenderType() == 1) {
            ArticleRespDto respDto = articleApi.getByTitleOrSort(createReqVO.getContent());
            createSystemAnswerCustomerMessage(createReqVO,
                    Objects.nonNull(respDto) && StringUtils.isNoneEmpty(respDto.getContent()) ? respDto.getContent() : customerMessageAnswer);
            return createCustomerMessage(createReqVO);
        }
        return BeanUtil.toBean(customerMessage, AppCustomerMessageRespVO.class);
    }

    /**
     * 创建系统应答消息
     * @param message
     * @param content
     * @return
     */
    private void createSystemAnswerCustomerMessage(AppCustomerMessageReqVO message, String content) {
        message.setContent(content);
        message.setSenderType(2);//系统
        if (message.getSendTime() != null) {
            message.setSendTime(LocalDateTime.now().plusSeconds(1L));
        }
    }


    @Override
    public void updateCustomerMessage(CustomerMessageSaveReqVO updateReqVO) {
        // 校验存在
        validateCustomerMessageExists(updateReqVO.getId());
        // 更新
        CustomerMessageDO updateObj = BeanUtils.toBean(updateReqVO, CustomerMessageDO.class);
        customerMessageMapper.updateById(updateObj);
    }

    @Override
    public void deleteCustomerMessage(Long id) {
        // 校验存在
        validateCustomerMessageExists(id);
        // 删除
        customerMessageMapper.deleteById(id);
    }

    private void validateCustomerMessageExists(Long id) {
        if (customerMessageMapper.selectById(id) == null) {
            throw exception(CUSTOMER_MESSAGE_NOT_EXISTS);
        }
    }

    @Override
    public CustomerMessageDO getCustomerMessage(Long id) {
        return customerMessageMapper.selectById(id);
    }

    @Override
    public PageResult<CustomerMessageDO> getCustomerMessagePage(CustomerMessagePageReqVO pageReqVO) {
        return customerMessageMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<CustomerMessageDO> getCustomerMessagePage(AppCustomerMessagePageReqVO pageReqVO) {
        LoginUser loginUser = Optional.ofNullable(SecurityFrameworkUtils.getLoginUser())
                .orElseThrow(() -> new ValidateException("用户未登录"));
        pageReqVO.setUserId(loginUser.getId());
        CustomerMessagePageReqVO reqVO = BeanUtil.toBean(pageReqVO, CustomerMessagePageReqVO.class);
        return getCustomerMessagePage(reqVO);
    }

}